﻿using System;
using System.IO;
using System.Text;
using System.Windows.Controls;

namespace FieldTools.Client.Command
{
    /// <summary>
    /// 将console输出定向到TextBox中
    /// </summary>
    public class TextBoxWriter : TextWriter
    {
        TextBox textBox;
        delegate void WriteFunc(string value);
        WriteFunc write;
        WriteFunc writeLine;

        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="textBox"></param>
        public TextBoxWriter(TextBox textBox)
        {
            this.textBox = textBox;
            write = Write;
            writeLine = WriteLine;
        }

        /// <summary>
        /// 使用UTF-16避免不必要的编码转换
        /// </summary>
        public override Encoding Encoding
        {
            get { return Encoding.Unicode; }
        }


        /// <summary>
        /// 最低限度需要重写的方法
        /// </summary>
        /// <param name="value"></param>
        public override void Write(string? value)
        {
            Action action = () =>
            {
                textBox.AppendText(value);
                textBox.ScrollToEnd();
            };
            textBox.Dispatcher.Invoke(action);
            //if (textBox.IsInputMethodEnabled)
            //else
            //textBox.AppendText(value);
        }

        /// <summary>
        /// 为提高效率直接处理一行的输出
        /// </summary>
        /// <param name="value"></param>
        public override void WriteLine(string? value)
        {
            Action action = () =>
            {
                textBox.AppendText(value);
                textBox.AppendText(NewLine);
                textBox.ScrollToEnd();
            };
            textBox.Dispatcher.Invoke(action);
            //if (textBox.IsInputMethodEnabled)
            //    textBox.Dispatcher.Invoke(writeLine, value);
            //else
            //{
            //textBox.AppendText(value);
            //    textBox.AppendText(this.NewLine);
            //}
        }
    }
}
